package com.pennywise.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.pennywise.model.Transaction;
import com.pennywise.model.excel.TransactionExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Excel工具类
 * 使用EasyExcel处理Excel导出
 */
@Slf4j
@Component
public class ExcelUtil {
    
    /**
     * 导出交易记录到Excel
     *
     * @param transactions 交易记录列表
     * @param filePath 导出文件路径
     */
    public void exportTransactions(List<Transaction> transactions, String filePath) {
        log.info("开始导出交易记录到Excel，记录数: {}", transactions.size());
        
        List<TransactionExcel> excelData = transactions.stream()
                .map(this::convertToExcelModel)
                .collect(Collectors.toList());
        
        try {
            EasyExcel.write(filePath, TransactionExcel.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("交易记录")
                    .doWrite(excelData);
            
            log.info("Excel导出成功，文件路径: {}", filePath);
        } catch (Exception e) {
            log.error("Excel导出失败", e);
            throw new RuntimeException("Excel导出失败: " + e.getMessage());
        }
    }
    
    /**
     * 将Transaction转换为TransactionExcel
     */
    private TransactionExcel convertToExcelModel(Transaction transaction) {
        TransactionExcel excel = new TransactionExcel();
        BeanUtils.copyProperties(transaction, excel);
        return excel;
    }
} 